<?php


namespace app\index\model;


use think\Exception;
use think\Model;

class MenuRole extends Model
{
    /**
     * getUserMenu
     * 获取用户菜单
     * @url
     * @method
     * @param array $user_data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/25
     */
    public static function getUserMenu($user_data): array
    {
        $MenuRoleClass=new self();
        $MenuClass=new Menu();
        if($user_data['role']===1){
            $menu=$MenuClass->where('del_flag',0)->column('url_path');
        }else{
            $menu= $MenuRoleClass->alias('mr')
                ->join('__MENU__ m','mr.menu_id=m.id','left')
                ->where('mr.del_flag',0)
                ->where(function ($query) use ($user_data) {
                    $query->where('mr.user_id', $user_data['id']);
                    if ($user_data['role']) {
                        $query->whereOr('mr.role_id', $user_data['role']);
                    }
                    if ($user_data['role_detail_id']) {
                        $query->whereOr('mr.role_detail_id', $user_data['role_detail_id']);
                    }
                    if ($user_data['group_id']) {
                        $query->whereOr('mr.group_id', $user_data['group_id']);
                    }
                })
                ->group('mr.menu_id')
                ->column('m.url_path');
        }
        return $menu;
    }

    /**
     * getMenuByUser
     * 获取当前用户权限的菜单id
     * @url
     * @method
     * @param int $user 用户id
     * @return array|bool|string
     * @author Asira
     * @date 2021/1/25
     */
    public static function getMenuByUser($user){
        $MenuRoleClass=new self();

        return $MenuRoleClass->alias('mr')->join('__MENU__ m','mr.menu_id=m.id','left')->where('mr.user_id','=',$user)->where('m.p_id','<>','0')->where('mr.del_flag',0)->column('m.id');
    }

    /**
     * updateMenuUser
     * 更新用户权限菜单
     * @url
     * @method
     * @param int $id 用户id
     * @param array $menu 菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/25
     */
    public static function updateMenuUser($id, $menu): array
    {
        $MenuRoleClass=new self();
        $UserClass=new User();
        $role=$UserClass->where('id',$id)->where('del_flag',0)->field('id')->find();
        if(empty($role)){
            return ['status'=>false,'result'=>'未找到数据'];
        }
        $menu_list=$MenuRoleClass->where('user_id',$id)->field('id,menu_id,del_flag')->select()->toArray();
        $update=[];
        foreach ($menu_list as $key=>$value){
            $index=array_search($value['menu_id'],$menu,true);
            if($index!==false){
                unset($menu[$index]);
                $update[]=['id'=>$value['id'],'del_flag'=>0];
            }else{
                $update[]=['id'=>$value['id'],'del_flag'=>1];
            }
        }
        $insert=[];
        if(!empty($menu)){
            foreach ($menu as $key=>$value){
                $insert[]=['menu_id'=>$value,'user_id'=>$id];
            }
        }

        return self::updateRole($update,$insert);
    }

    /**
     * getMenuByRole
     * 获取当前级别权限的菜单id
     * @url
     * @method
     * @param int $role 级别id
     * @return array|bool|string
     * @author Asira
     * @date 2021/1/25
     */
    public static function getMenuByRole($role){
        $MenuRoleClass=new self();

        return $MenuRoleClass->alias('mr')->join('__MENU__ m','mr.menu_id=m.id','left')->where('mr.role_id','=',$role)->where('m.p_id','<>','0')->where('mr.del_flag',0)->column('m.id');
    }

    /**
     * updateMenuRole
     * 更新级别权限菜单
     * @url
     * @method
     * @param int $id 级别id
     * @param array $menu 菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/25
     */
    public static function updateMenuRole($id, $menu): array
    {
        $MenuRoleClass=new self();
        $RoleClass=new Role();
        $role=$RoleClass->where('id',$id)->where('del_flag',0)->field('id')->find();
        if(empty($role)){
            return ['status'=>false,'result'=>'未找到数据'];
        }
        $menu_list=$MenuRoleClass->where('role_id',$id)->field('id,menu_id,del_flag')->select()->toArray();
        $update=[];
        foreach ($menu_list as $key=>$value){
            $index=array_search($value['menu_id'],$menu,true);
            if($index!==false){
                unset($menu[$index]);
                $update[]=['id'=>$value['id'],'del_flag'=>0];
            }else{
                $update[]=['id'=>$value['id'],'del_flag'=>1];
            }
        }
        $insert=[];
        if(!empty($menu)){
            foreach ($menu as $key=>$value){
                $insert[]=['menu_id'=>$value,'role_id'=>$id];
            }
        }

        return self::updateRole($update,$insert);
    }

    /**
     * getMenuByRoleDetail
     * 获取当前角色权限的菜单id
     * @url
     * @method
     * @param int $role_detail 角色id
     * @return array|bool|string
     * @author Asira
     * @date 2021/1/25
     */
    public static function getMenuByRoleDetail($role_detail){
        $MenuRoleClass=new self();

        return $MenuRoleClass->alias('mr')->join('__MENU__ m','mr.menu_id=m.id','left')->where('mr.role_detail_id','=',$role_detail)->where('m.p_id','<>','0')->where('mr.del_flag',0)->column('m.id');
    }

    /**
     * updateMenuRoleDetail
     * 更新角色权限菜单
     * @url
     * @method
     * @param int $id 角色id
     * @param array $menu 菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author Asira
     * @date 2021/1/25
     */
    public static function updateMenuRoleDetail($id, $menu): array
    {
        $MenuRoleClass=new self();
        $RoleDetailClass=new RoleDetail();
        $role_detail=$RoleDetailClass->where('id',$id)->where('del_flag',0)->field('id')->find();
        if(empty($role_detail)){
            return ['status'=>false,'result'=>'未找到数据'];
        }
        $menu_list=$MenuRoleClass->where('role_detail_id',$id)->field('id,menu_id,del_flag')->select()->toArray();
        $update=[];
        foreach ($menu_list as $key=>$value){
            $index=array_search($value['menu_id'],$menu,true);
            if($index!==false){
                unset($menu[$index]);
                $update[]=['id'=>$value['id'],'del_flag'=>0];
            }else{
                $update[]=['id'=>$value['id'],'del_flag'=>1];
            }
        }
        $insert=[];
        if(!empty($menu)){
            foreach ($menu as $key=>$value){
                $insert[]=['menu_id'=>$value,'role_detail_id'=>$id];
            }
        }
        return self::updateRole($update,$insert);
    }

    /**
     * getMenuByGroup
     * 获取当前组权限的菜单id
     * @url
     * @method
     * @param $group
     * @return array|bool|string
     * @author Asira
     * @date 2021/1/25
     */
    public static function getMenuByGroup($group){
        $MenuRoleClass=new self();

        return $MenuRoleClass->alias('mr')->join('__MENU__ m','mr.menu_id=m.id','left')->where('mr.group_id','=',$group)->where('m.p_id','<>','0')->where('mr.del_flag',0)->column('m.id');
    }

    /**
     * updateMenuGroup
     * 更新组权限菜单
     * @url
     * @method
     * @param int $id 组id
     * @param array $menu 菜单
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/25
     */
    public static function updateMenuGroup($id, $menu): array
    {
        $MenuRoleClass=new self();
        $GroupClass=new Group();
        $group=$GroupClass->where('id',$id)->where('del_flag',0)->field('id')->find();
        if(empty($group)){
            return ['status'=>false,'result'=>'未找到数据'];
        }
        $menu_list=$MenuRoleClass->where('group_id',$id)->field('id,menu_id,del_flag')->select()->toArray();
        $update=[];
        foreach ($menu_list as $key=>$value){
            $index=array_search($value['menu_id'],$menu,true);
            if($index!==false){
                unset($menu[$index]);
                $update[]=['id'=>$value['id'],'del_flag'=>0];
            }else{
                $update[]=['id'=>$value['id'],'del_flag'=>1];
            }
        }
        $insert=[];
        if(!empty($menu)){
            foreach ($menu as $key=>$value){
                $insert[]=['menu_id'=>$value,'group_id'=>$id];
            }
        }
        return self::updateRole($update,$insert);
    }

    /**
     * updateRole
     * 更新权限菜单
     * @url
     * @method
     * @param $update
     * @param $insert
     * @return array
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/25
     */
    public static function updateRole($update, $insert): array
    {
        $MenuRoleClass=new self();

        $MenuRoleClass->startTrans();
        try{
            if(!empty($update)){
                $result=$MenuRoleClass->isUpdate(true)->saveAll($update);
                if($result===false){
                    return ['status'=>false,'result'=>'更新菜单失败'];
                }
            }
            if(!empty($insert)){
                $result=$MenuRoleClass->isUpdate(false)->saveAll($insert);
                if($result===false) {
                    return ['status' => false, 'result' => '新增菜单失败'];
                }
            }
            $MenuRoleClass->commit();
            return ['status'=>true,'result'=>'更新成功'];
        }catch (Exception $e){
            $MenuRoleClass->rollback();
            trace('updateRole '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败'];
        }
    }

    public static function createMenuRole($role,$role_detail,$menu){
        $MenuRoleClass=new self();
        $RoleClass=new Role();
        $RoleDetailClass=new RoleDetail();

        $MenuRoleClass->startTrans();

        try{
            $role_data=$RoleClass->where('role_name', $role)->field('id')->find();
            if(empty($role_data)){
                $result=$RoleClass->insert(['role_name'=>$role],true);
                if($result===false){
                    return ['status'=>false,'result'=>'添加角色类别失败'];
                }
                $role_id=$result;
            }else{
                if(empty($role_detail)){
                    return ['status'=>false,'result'=>'请输入要创建的角色'];
                }
                $role_id=$role_data['id'];
            }
            if($role_detail){
                $role_detail_data=$RoleDetailClass->where('role_name',$role)->where('role_id',$role_id)->field('id')->find();
                if(!empty($role_detail_data)){
                    return ['status'=>false,'result'=>'角色名已存在'];
                }
                $result=$RoleDetailClass->insert(['role_name'=>$role_detail,'role_id'=>$role_id],true);
                if($result===false){
                    return ['status'=>false,'result'=>'添加角色失败'];
                }
                $role_detail_id=$result;
            }

            if(!empty($menu)){
                $insert=[];
                foreach ($menu as $key=>$value){
                    empty($role_data)&&$insert[]=['role_id'=>$role_id,'menu_id'=>$value];
                    isset($role_detail_id)&&$insert[]=['role_detail_id'=>$role_id,'menu_id'=>$value];
                }
                $result=$MenuRoleClass->isUpdate(false)->saveAll($insert);
                if($result===false){
//                    throw Exception('添加权限失败');
                    return ['status'=>false,'result'=>'添加权限失败'];
                }
            }
            $MenuRoleClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (Exception $e){
            $MenuRoleClass->rollback();
            trace('createMenuRole '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'创建失败'];
        }
    }

    public static function createMenuRoleGroup($group,$menu){
        $MenuRoleClass=new self();
        $GroupClass=new Group();

        $group_data=$GroupClass->where('group_name',$group)->field('id')->find();
        if(!empty($group_data)){
            return ['status'=>false,'result'=>'组名已被占用'];
        }
        $MenuRoleClass->startTrans();
        try{
            $result=$GroupClass->insert(['group_name'=>$group],true);
            if($result===false){
                return ['status'=>false,'result'=>'添加组失败'];
            }
            $group_id=$result;
            if(!empty($menu)){
                $insert=[];
                foreach ($menu as $key=>$value){
                    $insert[]=['group_id'=>$group_id,'menu_id'=>$value];
                }
                $result=$MenuRoleClass->isUpdate(false)->saveAll($insert);
                if($result===false){
                    return ['status'=>false,'result'=>'添加权限失败'];
                }
            }
            $MenuRoleClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch(Exception $e){
            $MenuRoleClass->rollback();
            trace('createMenuRoleGroup'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'创建失败'];
        }
    }
}